<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/7
 * Time: 1:51
 */

namespace app\api\controller\v19;

use app\api\controller\v2\Auth;
use app\common\cachemodel\AppQq;
use app\common\cachemodel\AppWeibo;
use app\common\cachemodel\MiniAppUser;
use app\common\cachemodel\Recode;
use app\common\cachemodel\Wechat;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\Rectification as RectificationModel;
use app\common\model\User;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use think\Db;
use think\Log;
use think\response\Json;
use XznsTools\cache\CacheManage;

/**个人信息修改接口
 * @title
 * @desc
 * @url
 * @version 2.2.0
 * Class Demo
 * @package app\api\controller\v2
 */
class Info extends Auth
{
    protected $msg;


    /**
     * 三方绑定
     * @return Json
     * @throws ApiException
     * @throws GuzzleException
     */
    public function bind_third()
    {
        $param = input('param.param');
        $param = $param ? json_decode($param, true) : [];
        $type = input('param.type/d');
        $this->msg = '';
        switch ($type)
        {
            case 1:
                $res = $this->wechat($param);
                break;
            case  2:
                $res = $this->qq($param);
                break;
            case  3:
                $res = $this->weibo($param);
                break;
            default:
                return show(config('code.error'), '未知的账号');
                break;
        }
        if ($this->msg)
        {
            return show(config('code.error'), $this->msg);
        }
        return show(200, '绑定成功', ['nickname' => $res]);
    }

    /**
     * 微信登录
     * @param $param
     * @return string
     * @throws ApiException
     * @throws Exception
     */
    protected function wechat($wechat_user)
    {
        //检测用户是否已绑定
        $WechatModel = new Wechat();
        $user_wechat = $WechatModel->getWechatInfo($this->user['id'], 2);
        if ($user_wechat)
        {
            $this->msg = '您已绑定微信';
            return false;
        }
        //验证是否注册过
        $User = (new Wechat())->getWechatInfo($wechat_user['unionid']);
        if ($User)
        {
            $this->msg = '当前微信已被注册';
            return false;
        }
        try
        {
            $wechat_insert = [
                'uid' => $this->user['id'],
                'nickname' => $wechat_user['nickname'] ?? '匿名用户',
                'sex' => $wechat_user['sex'] ?? 2,
                'city' => $wechat_user['city'] ?? '',
                'province' => $wechat_user['province'] ?? '',
                'country' => $wechat_user['country'] ?? '',
                'headimgurl' => $wechat_user['headimgurl'] ?? '',
                'openid' => $wechat_user['openid'],
                'unionid' => $wechat_user['unionid'],
                'create_time' => time(),
                'update_time' => time(),
            ];
            //qq表生成数据
            $WechatModel->SaveData($wechat_insert);

            // 小程序绑定
            $miniUsers = (new MiniAppUser())->where(['unionid' => $wechat_user['unionid'], 'status' => 0, 'mini_type' => 'WEAPP'])->column('id');
            if ($miniUsers)
            {
                // 更新数据库状态
                (new MiniAppUser())->where(['unionid' => $wechat_user['unionid'], 'status' => 0, 'mini_type' => 'WEAPP'])->update(['uid' => $this->user['id']]);
                // 删除缓存
                foreach ($miniUsers as $mid)
                {
                    CacheManage::getInstance()->setCacheConfig('miniapp.user', $mid)->rmCache();
                }
            }

            return $wechat_user['nickname'];
        }
        catch (\Exception $e)
        {
            $this->msg = '微信绑定失败';
        }
        return false;
    }

    /**
     * QQ登录
     * @param $param
     * @return string
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    protected function qq($param)
    {
        //检测用户是否已绑定
        $QqModel = new AppQq();
        $user_qq = $QqModel->getUserQqInfoFromCache($this->user['id'], 2);
        if ($user_qq)
        {
            return $this->msg = '您已绑定qq';
        }
        // 获取用户qq信息
        $qq_user = $QqModel->QqInfo($param);
        // 验证是否注册过
        $User = (new AppQq())->getUserQqInfoFromCache($qq_user['unionid']);
        if ($User)
        {
            $this->msg = '当前qq号已被注册';
            return false;
        }
        try
        {
            $qq_insert = [
                'uid' => $this->user['id'],
                'openid' => $param['openid'],
                'unionid' => $qq_user['unionid'],
                'create_time' => time(),
                'nickname' => $qq_user['nickname'],
                'sex' => $qq_user['sex'],
                'avatar' => $qq_user['figureurl_qq_1'],
            ];
            //qq表生成数据
            (new AppQq())->SaveData($qq_insert);
            return $qq_user['nickname'];
        }
        catch (\Exception $e)
        {
            $this->msg = 'qq绑定失败';
        }
        return false;
    }

    /**
     * 微博登录
     * @param $param
     * @return string
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    protected function weibo($param)
    {
        $WbModel = new AppWeibo();
        //检测用户是否已绑定微博
        $user_wb = $WbModel->getUserWbInfoFromCache($this->user['id'], 2);
        if ($user_wb)
        {
            $this->msg = '您已绑定微博';
            return false;
        }
        // 获取weibo信息
        $wb_user = $WbModel->WeiboInfo($param);
        // 验证当前微博是否注册过
        $User = (new AppWeibo())->getUserWbInfoFromCache($param['uid']);
        if ($User)
        {
            $this->msg = '当前微博已被注册';
            return false;
        }
        try
        {
            $wb_insert = [
                'uid' => $this->user['id'],
                'wbuid' => $param['uid'],
                'create_time' => time(),
                'nickname' => $wb_user['name'],
                'sex' => $wb_user['sex'],
                'avatar' => $wb_user['profile_image_url'],
            ];
            //wb表生成数据
            (new AppWeibo())->SaveData($wb_insert);
            return $wb_user['name'];
        }
        catch (\Exception $e)
        {
            $this->msg = '微博绑定失败';
        }
        return false;
    }
}
